Skip to content

history: accumulate products without building them first - #1162

Draft
TillRasmussen wants to merge 7 commits into
CICE-Consortium:mainfrom
TillRasmussen:history-accum-scale
Draft

TillRasmussen wants to merge 7 commits into
CICE-Consortium:mainfrom
TillRasmussen:history-accum-scale

Conversation

@TillRasmussen

@TillRasmussen TillRasmussen commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

PR checklist

  • Short (1 sentence) summary of your PR:
    Small Refactor of history accumulation
  • Developer(s):
    @TillRasmussen with support from Claude
  • Suggest PR reviewers from list in the column to the right. @apcraig @dabail10 @anton-seaice
  • Please copy the PR test results link or provide a summary of testing completed below.
    Test has been run local. No test cover history files.
  • How much do the PR code changes differ from the unmodified code?
    • bit for bit
    • different at roundoff level
    • more substantial
  • Does this PR create or have dependencies on Icepack or any other models?
    • Yes
    • No
  • Does this PR update the Icepack submodule? If so, the Icepack submodule must point to a hash on Icepack's main branch.
    • Yes
    • No
  • Does this PR add any new test cases?
    • Yes
    • [ x] No
  • Is the documentation being updated? ("Documentation" includes information on the wiki or in the .rst files from doc/source/, which are used to create the online technical docs at https://readthedocs.org/projects/cice-consortium-cice/. A test build of the technical docs will be performed as part of the PR testing.)
    • Yes
    • [ x] No, does the documentation need to be updated at a later time?
      • Yes
      • [ x] No
  • Please document the changes in detail, including why the changes are made. This will become part of the PR commit log.
    Seventy-two calls to accum_hist_field pass a product as the actual argument -- aice(:,:,iblk)trcr(:,:,nt_alvl,iblk) in mechred, sk_ltrcr(:,:,nt_bgc_N(n),iblk) in bgc, and so on. Each makes the compiler evaluate the product into a temporary over the whole block, nx_block by ny_block, pass it, and discard it.

accum_hist_field_2D reads only ilo:ihi by jlo:jhi under tmask, so most of that temporary is computed and never read: for a 10x12 block with nghost=2 it is 224 products to produce 120. The waste is the ghost region, and it is paid once per field per block per history step.

Nothing is reordered: the operands and the sequence multiply-then-add are identical before and after. If optimization flags are applied the history file may change on round off level but this do not propagate into the rest of the model thus restart and log files should be bit for bit.

Despite the gain it is not expected that this will change the run time in the block version. The main argument for including it here is the conversion to compressed arrays.

Verified bit-for-bit against unmodified upstream on gx3, both gfortran and ifx: every restart and history data file identical, only the history header creation stamp differs.

Three specifics are added to the generic instead, taking the factors and combining them in the loop that was already running:

accum_hist_field_2D_prod two fields a(i,j)*b(i,j)
accum_hist_field_2D_mul field by a scalar a(i,j)*s

The approach for velocity to speed conversions has been changed and the usage of work arrays has been passed based on calculations outside the call to accum_hist_field. These and others have more than two inputs and it was judged that there was no need to calculate more accum_hist_field.

Seventy-two calls to accum_hist_field pass a product as the actual
argument -- aice(:,:,iblk)*trcr(:,:,nt_alvl,iblk) in mechred,
sk_l*trcr(:,:,nt_bgc_N(n),iblk) in bgc, and so on.  Each makes the
compiler evaluate the product into a temporary over the whole block,
nx_block by ny_block, pass it, and discard it.

accum_hist_field_2D reads only ilo:ihi by jlo:jhi under tmask, so most of
that temporary is computed and never read: for a 10x12 block with
nghost=2 it is 224 products to produce 120.  The waste is the ghost
region, and it is paid once per field per block per history step.

Three specifics are added to the generic instead, taking the factors and
combining them in the loop that was already running:

  accum_hist_field_2D_prod  two fields          a(i,j)*b(i,j)
  accum_hist_field_2D_mul   field by a scalar   a(i,j)*s
  accum_hist_field_2D_smul  scalar by a field   s*a(i,j)

The third exists so that converting a caller whose scale is on the left
is still a one-character change and a reviewer never has to check that a
reordering was safe.  Its dummies are named sfac/afld rather than s/a
because two specifics differing only in argument ORDER are ambiguous for
keyword calls, which is a compile error and not a silent one.

BIT-FOR-BIT, AND WHY

Nothing is reordered: the operands and the sequence multiply-then-add are
identical before and after.  The only mechanism that could move a bit is
FMA contraction -- fusing the multiply and the add into one rounding --
which becomes possible once the two are in the same loop body rather than
in separate procedures either side of an array temporary.

That cannot happen on any shipped configuration.  Of the 84 Macros, 25
carry an FMA-capable arch flag (-xHost, -xCORE-AVX*, -march=) and every
one of those also carries -fp-model precise, source or strict, which
suppresses contraction -- verified with ifx 2025.3: -O2 -xHost emits
vfmadd, -O2 -xHost -fp-model precise does not.  The remaining 59 set no
FMA-capable arch flag, so the instruction is not available to begin with.
Zero are exposed.

Even where a custom build did enable contraction, it could not reach the
model.  a2D is referenced only in cicecore/cicedyn/analysis/ice_history*
and the three io/*/ice_history_write.F90; no dynamics module, ice_state
or ice_flux reads it, and nothing feeds it back into the prognostic
state.  The trajectory and the restart file are unaffected; only history
output could differ, and only in the last bits.

Verified bit-for-bit against unmodified upstream on gx3, both gfortran
and ifx: every restart and history data file identical, only the history
header creation stamp differs.

@anton-seaice anton-seaice left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


! The scale on the left. A separate specific rather than swapping the
! arguments at the call site, so that converting a caller is a one-character
! change and a reviewer never has to check that a reordering was safe.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe i'm misunderstanding here. I think i'm ok with forcing the scalar to the be the second argument.

Then it just wouldn't compile if someone wrote

accum_hist_field_2D_mul(n_siconc, iblk, c100, aice(:,:,iblk), a2D)

?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The second should have been caught (2 arrays). Nice catch.
The first will require a function with 4 inputs.

I agree with your comment that there is no need to have both the scalar,array version and the array,scalar version. I will remove one.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please do a manual grep for use of accum_hist_field in the code and make the appropriate changes everywhere. Don't rely entirely on AI if that's how a few calls were missed. Thanks.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will do. Admitted. This was added quicker than I wanted to have it as a potential discussion point for what to do with the along the way findings that should be pushed.

@apcraig

apcraig commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

@TillRasmussen, these changes looked useful. Why did you close the PR. I think as you find improvements separate from the "1d" development, you should PR them to main including stuff like the excess memory use in the remap advection.

@TillRasmussen

TillRasmussen commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

@apcraig I am fixing the different issues and I did not want you to spend time on it while doing so. It will be up again.

@apcraig

apcraig commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

The PR can stay, we know it's in review and undergoing revisions (use the "PR: something" labels), like "PR:in-review" and "PR: waiting-on-developer". Then push the update to the PR and update the labels, turning on "PR: ready-for-review" again. That's a very standard way to operate. Closing and reopening the PR loses all the history of review and other comments.

The accumulator's specific forms cover a field and a field scaled by a
constant.  Anything more involved -- a product of three factors, a
difference, a quotient by dt, a sign flip -- would need a variant per
operator combination, so those callers now compute into a work array and
pass it plain.  That is already the idiom in ice_history_snow, which needs
no change here because every one of its callers is in this form.

The scalar-first specific is gone.  Callers whose scale sat on the left
swap their two actuals instead, which is bit-for-bit: floating
multiplication is commutative and exactly rounded.

Work arrays added where the routine had none, and workc joins the OMP
PRIVATE clause in accum_hist -- it is declared in the routine that carries
the directive, unlike the locals of the accum_hist_* routines called from
inside the loop, which are private by construction.

Verified against the unmodified base on gfortran and ifx, bit-for-bit over
history and restart alike.  The standard templates could not have shown
this: they run ktherm=-1 with ponds, FSD, BGC, aerosols and isotopes off,
so they exercise almost none of the fields touched here.  The check used a
configuration with every tracer on and all 279 history fields enabled.
@TillRasmussen TillRasmussen reopened this Nov 13, 2026
Five callers were missed: f_albsni, whose argument is a four-term weighted
sum, and the four ridge fields whose second factor is (c1 - trcr(...)).

They were missed because the scan that found the others stripped anything
inside parentheses before looking for operators -- so it would not mistake a
subscript for arithmetic -- and an expression wrapped in its own parentheses
then looks like one subscript and comes back operator-free.  The scan also
only examined the argument before the accumulator, which is the second factor
only in the two-field form.  Peeling one layer of wrapping parentheses and
checking EVERY field argument finds all five and reports none remaining.

albsni builds its sum in a work array.  The ridge fields keep the two-field
specific -- that is what it is for -- and only the (c1 - trcr) factor moves
to a work array, so no anonymous temporary is built for it.

Verified against the unmodified base on gfortran, bit-for-bit over all five
history files and all 36 restart files, with every tracer enabled and all 279
history fields on.
@TillRasmussen

Copy link
Copy Markdown
Contributor Author

The structure is changed as including a new version of acumm_hist_field for all number of variables and arithmetic become two much. Instead a temporary (work) has been used to forward this to the call wihout having calculations in the call itself.

Every work-array expression ran over the whole block, halo included.  The
accumulators read jlo..jhi x ilo..ihi and nothing else, so the halo result
was built and discarded -- 13% of each assignment on a gx3 block.

The waste is not the reason to change it.  A full-array expression EVALUATES
across the halo, where a value may be uninitialised; with -finit-real=snan
that is a floating-point trap on a result nobody wanted.  In ice_history the
operands are state arrays the halo updates keep defined, so this was latent
rather than live, but it is the wrong default.

All 74 statements now run ilo:ihi, jlo:jhi.  That is 41 which predate this
branch -- the split is upstream's, not new here: when upstream uses a work
array it writes the full array, and when it needs per-cell logic it writes a
scoped loop.  The explicit loops are left alone; they exist where a per-cell
condition needs them and are already scoped.

accum_hist_snow and accum_hist_mechred had no block geometry at all and now
take this_block and the four bounds.  In accum_hist_pond the bounds existed
but were set BELOW the work arrays, so scoping them alone gave ilo = 0 and an
index-zero abort; the block moves above its first use.

Bit-for-bit against the unmodified base: all five history files and all 36
restart files, every tracer on, all 279 history fields.
@apcraig

apcraig commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

@TillRasmussen, let us know when this is ready for review again.

@TillRasmussen

Copy link
Copy Markdown
Contributor Author

It should be ready to review again.

Note the change for calls to accum_hist_field with more than 2 arguments. do the calculation based on a work array and pass that instead.

@apcraig apcraig left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you verified that all calls to accum_hist_field that should be modified have been modified?

Double check indentation and line continuation in these changes.

Wondering about consistent use of loops vs array syntax in the implementation.

Wondering about why some places are computing hist field diagnostics at all block points and others only in the interior.

Can we be sure that accum_hist_fields will never accumulate on the halo? Should we change the interface so we just pass array(ilo:ihi,jlo:jhi). I guess that might slow things down passing array subsections?

endif
if (f_icedir(1:1) /= 'x') then
worka(:,:) = c0
worka(ilo:ihi,jlo:jhi) = c0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is partially filling an array really saving a lot of time. Do we have to worry about stale or uninitialized values being passed/used/trapped in the worka array?

(uvelN(:,:,iblk)*uvelN(:,:,iblk)) + &
(vvelN(:,:,iblk)*vvelN(:,:,iblk))), a2D)
if (f_icespdN (1:1) /= 'x') then
worka(ilo:ihi,jlo:jhi) = sqrt( (uvelN(ilo:ihi,jlo:jhi,iblk)*uvelN(ilo:ihi,jlo:jhi,iblk)) + (vvelN(ilo:ihi,jlo:jhi,iblk)*vvelN(ilo:ihi,jlo:jhi,iblk)))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add line continuation?

call accum_hist_field(n_fsensn_ai-n2D, iblk, ncat_hist, &
fsensn(:,:,1:ncat_hist,iblk)*aicen_init(:,:,1:ncat_hist,iblk), a3Dc)
if (f_fsurfn_ai (1:1) /= 'x') then
workc(:,:,1:ncat_hist) = fsurfn(:,:,1:ncat_hist,iblk)*aicen_init(:,:,1:ncat_hist,iblk)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are you precomputing the work arrays with ilo:ihi,jlo:jhi some places and not others?

call accum_hist_field(n_dafsd_weld-n3Dacum, iblk, nfsd_hist, &
d_afsd_weld(:,:,1:nfsd_hist,iblk)/dt, a3Df)
if (f_dafsd_newi(1:1)/= 'x') then
worke(:,:,1:nfsd_hist) = d_afsd_newi(:,:,1:nfsd_hist,iblk)/dt

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We seem to be mixing loops (see lines 460:470 above) with array syntax for the same kind of calculations. Should we be consistent? Also, indentation seems to be a little inconsistent in this file, but that seems to be largely historic and not necessarily an issue with this PR alone.

vicen(:,:,1:ncat_hist,iblk) &
* (c1 - trcrn(:,:,nt_vlvl,1:ncat_hist,iblk)), a3Dc)
if (f_ardgn(1:1)/= 'x') then
workc(:,:,1:ncat_hist) = aicen(:,:,1:ncat_hist,iblk) &

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indentation is not consistent with other parts of this subroutine/file.

if (f_hpond_ai(1:1)/= 'x') &
call accum_hist_field(n_hpond_ai, iblk, aice_init(:,:,iblk)*worka(:,:)*trcr(:,:,nt_hpnd,iblk), a2D)
call accum_hist_field(n_hpond, iblk, worka(:,:),trcr(:,:,nt_hpnd,iblk), a2D)
if (f_hpond_ai(1:1)/= 'x') then

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again, lots of places where indentation is not as consistent as it could be.

* trcrn(:,:,nt_hpnd,1:ncat_hist,iblk), a3Dc)
if (f_hpondn (1:1) /= 'x') then
workc(:,:,1:ncat_hist) = trcrn(:,:,nt_apnd,1:ncat_hist,iblk) &
* trcrn(:,:,nt_hpnd,1:ncat_hist,iblk)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

indentation


do j = jlo, jhi
do i = ilo, ihi
if (tmask(i,j,iblk)) then

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know this isn't a question about these changes because accum_hist_field_2D established the standard, but why is tmask hardwired here? What if the field is not on the T grid? Is this an oversight that doesn't happen to cause problems because tmask is a supermask of u and other potential grid masks? Or is this somehow correct and intentional?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We did roughly agree this should be changed, see #1064

@TillRasmussen

Copy link
Copy Markdown
Contributor Author

I think that this requires that we set up some rules. For this. If we use different mask we need to initialize all at first and we cannot pass the variable itself.

Those rules should then be

  1. All pass a work array that is init to 0.
  2. Mask should vary according to their native place of calculation. (B velocities use umask, C velocities c mask....)
  3. Masked values are zero.

@apcraig

apcraig commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

OK, looks like there was another refactor. Let me summarize the current changes overall,

  • You added accum_hist_field_2D_speed, accum_hist_field_2D_prod and accum_hist_field_2D_mul.
  • You added masks an optional arguments to the accum_hist_field subroutines.
  • There are changes to the calls to accum_hist_field to leverage the changes

Comments:

  • It's unfortunate/fortunate the accum_hist_field_2D_speed is not part of the overloaded subroutine. I'm not yet sure how I feel about that, but I think it's OK.
  • There are still places where you precomute the arrays sent into accum_hist_field with ilo:ihi,jlo:jhi and others that are the full array. Why is that inconsistent and which is the "right" way to do this? Lets make this consistent, yes?
  • Where mask was added as an optional argument to the accum_hist_field subroutines, that variable should be declared higher in the variable list. In general, after the subroutine declaration, the arguments are declared, THEN the local variables are declared. You have the optional mask declared at the bottom of the local variables.
  • Are there any places where you pass the mask into accum_hist_field? Should that be added? Has this change been tested?
  • There are still places where the code changes are not indented properly.
  • Some of the added comments are a little confusing and could be clarified.
  • What tests have been run so far, have you verified that history files are bit-for-bit for all the history fields?

…rays

Five fields computed sqrt(a*a + b*b) inline over the physical domain, each
with its own loop.  accum_hist_field_2D_speed takes the two components and
does it once; icespd, icespdN, icespdE, atmspd and ocnspd now call it.  It
is public by name rather than through the generic interface: its signature
is indistinguishable from the _prod accumulator, which takes two fields and
multiplies them.

All six 2D accumulators gain an optional mask.  Absent, they fall back to
tmask exactly as before, so every existing call is unchanged; the predicate
is hoisted out of the i loop.

The work arrays were left undefined outside the physical domain, holding
whatever the previous field had put there.  They are now zeroed once per
block, after the bounds are taken and before first use.  The zero is a
constant store over the whole array; the computations stay scoped to
ilo:ihi, jlo:jhi, because a full-array expression would evaluate across the
halo where an operand may be uninitialised -- with -finit-real=snan that is
a trap on a result nobody wanted.  That is the rule the previous commit
established and this one keeps.

Zeroing once per block rather than per use costs one pass instead of
thirteen, and the branch in accum_hist_pond that could leave worka unset
carries the zero in its else arm instead.

workc needed nothing: every assignment already spans its full extent.

Verified against upstream d92f18a on gx3, history output identical in
every configuration tried: histall, fsdww, hist3d, bgc, restore5 and evpCD,
and a 309-field all-tracer case covering ice_history_snow, _fsd and _pond
together.
@TillRasmussen

TillRasmussen commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

OK, looks like there was another refactor. Let me summarize the current changes overall,

  • You added accum_hist_field_2D_speed, accum_hist_field_2D_prod and accum_hist_field_2D_mul.
  • You added masks an optional arguments to the accum_hist_field subroutines.
  • There are changes to the calls to accum_hist_field to leverage the changes

Comments:

  • It's unfortunate/fortunate the accum_hist_field_2D_speed is not part of the overloaded subroutine. I'm not yet sure how I feel about that, but I think it's OK.
    I would have liked to include it but it had the same number of arrays as multiplication. Then we should add an option to differentiate?
  • There are still places where you precomute the arrays sent into accum_hist_field with ilo:ihi,jlo:jhi and others that are the full array. Why is that inconsistent and which is the "right" way to do this? Lets make this consistent, yes?
    I am not sure that there is a right and wrong. A few thoughts
    Data outside ilo:ihi,jlo:jhi:
    is not used then why calculate them?
    How does the compiler pass those arrays?
    We dont know what is on the halo. It may be nan. If one calculates based on that a debugging run could fail and state that it met a NAN.

I think that my version would be initialization should do all: array(:,:)=c0 and calculations should follow array(ilo:ihi,jlo:jhi)= "some calculation"
I dont know why some arrays are initialized and some not. One may get into problems with changing mask.
In general I dont have strong opinion on which way to do it.

  • Where mask was added as an optional argument to the accum_hist_field subroutines, that variable should be declared higher in the variable list. In general, after the subroutine declaration, the arguments are declared, THEN the local variables are declared. You have the optional mask declared at the bottom of the local variables.
    Ok
  • Are there any places where you pass the mask into accum_hist_field? Should that be added? Has this change been tested?
    I will change a few velocities and speed arrays to test. I included it in order to follow the issue that Anton linked to.
  • There are still places where the code changes are not indented properly.
    I will go through when we define it.
  • Some of the added comments are a little confusing and could be clarified.
    I will look at it
  • What tests have been run so far, have you verified that history files are bit-for-bit for all the history fields?

I have run test of all except for bgc. When bgc is turned on it floods the log files with 10's of GB of warnings that some bgc routine has an issue. Nothing related to this work. That flooded my harddisk...

@apcraig

apcraig commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

With regard to computing the history fields over ilo:ihi,jlo:jhi or over the entire block, I suggest this is a good time to come up with a consistent implementation and update the code.

@TillRasmussen
TillRasmussen marked this pull request as draft November 18, 2026 17:38
Till Rasmussen added 2 commits November 19, 2026 14:48
Pad the field and index names in the accum_hist_field calls so the commas
line up, and join the two-line calls that no longer need to wrap.  Where a
single call sat under if (...) then / endif, it becomes the one-statement
if (...) & form.

The work arrays are now zeroed over the whole block before use and
computed over the physical domain only, which is the convention settled
with upstream: worka(:,:) = c0 first, then worka(ilo:ihi,jlo:jhi) = ...
The zeroing moves ahead of the loop rather than sitting inside it.

accum_hist_fsd had no block geometry at all -- it looped over nx_block and
ny_block -- so it gains the ilo/ihi/jlo/jhi bounds, the this_block lookup
and the imports they need, placed before first use.

Four defects found while building it:

  - five j loops in ice_history_fsd bounded by ihi rather than jhi
  - one i loop bounded by a truncated 'ih'
  - ilo/ihi/jlo/jhi used in accum_hist_fsd without being declared
  - two endifs left behind where if/then/endif became the one-statement
    form, after f_sivol and f_sisnthick.  Each silently closed the outer
    if (allocated(a2D)) block, so the compiler reported the error several
    hundred lines later at an unrelated endif.

Bit-for-bit against upstream d92f18a on gfortran and ifx: histall, fsdww,
hist3d, bgc, restore5, evpCD and a 309-field all-tracer case covering
ice_history_snow, _fsd and _pond.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants